//
//  NSDictionary+YHCommon.m
//  YHBaseProject
//
//  Created by 刘宇航 on 2018/5/1.
//  Copyright © 2018 lyh. All rights reserved.
//

#import "NSDictionary+XMCommon.h"


@implementation NSDictionary (XMCommon)
- (NSString *)toString:(NSString *)aKey {
    if ([self isKindOfClass:[NSDictionary class]]) {
        id idval = [self objectForKey:aKey];
        if ([idval isKindOfClass:[NSNull class]] || idval == [NSNull null]) {
            return @"";
        }
        if (idval && idval != [NSNull null]) {
            if ([idval respondsToSelector:@selector(length)]) {
                return [self objectForKey:aKey];
            } else if ([idval respondsToSelector:@selector(intValue)]) {
                return [NSString stringWithFormat:@"%d", [[self objectForKey:aKey] intValue]];
            }
        } else {
            return @"";
        }
        return @"";
    } else {
        return @"";
    }
}

- (int)toInt:(NSString *)aKey {
    if ([self isKindOfClass:[NSDictionary class]]) {
        id idval = [self objectForKey:aKey];
        if (idval && idval != [NSNull null] && [idval respondsToSelector:@selector(intValue)]) {
            return [[self objectForKey:aKey] intValue];
        } else {
            return 0;
        }
        return 0;
    } else {
        return 0;
    }
}

- (float)toFloat:(NSString *)aKey {
    if ([self isKindOfClass:[NSDictionary class]]) {
        id idval = [self objectForKey:aKey];
        if (idval && idval != [NSNull null] && [idval respondsToSelector:@selector(floatValue)]) {
            return [[self objectForKey:aKey] floatValue];
        } else {
            return 0;
        }
        return 0;
    } else {
        return 0;
    }
}

- (id)safe_objectForKey:(id)aKey {
    if (!aKey) {
        return nil;
    }
    return [self objectForKey:aKey];
}

/**
 读取本地JSON文件
 @param name 文件名字
 @param type 文件类型
 */
+ (NSDictionary *)readLocalFileWithName:(NSString *)name type:(NSString *)type {
    // 获取文件路径
    NSString *path = [[NSBundle mainBundle] pathForResource:name ofType:type];
    // 将文件数据化
    NSData *data = [[NSData alloc] initWithContentsOfFile:path];
    // 对数据进行JSON格式化并返回字典形式
    return [NSJSONSerialization JSONObjectWithData:data options:kNilOptions error:nil];
}

@end
